package com.cn.lotary.base.web;

import com.cn.lotary.base.dao.AbstractEntity;
import com.cn.lotary.base.dao.BaseDao;
import com.cn.lotary.util.LoggerUtils;
import java.util.List;
import java.util.Map;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SelectableDataModel;
import org.primefaces.model.SortOrder;

/**
 *
 * @author Jason 2012/06/27
 */
public class LazyEntityDataModel<T extends AbstractEntity> extends LazyDataModel<T> implements SelectableDataModel<T> {

    private static final long serialVersionUID = 1L;
    private String filter;
    private BaseDao<T> baseDao;

    /**
     *
     * @param filter eg: name = "jason", can not contains order by
     * @param baseDao BaseDao
     */
    public LazyEntityDataModel(String filter, BaseDao<T> baseDao) {
        //TODO:效率
        if (filter != null && !"".equals(filter) && (filter.contains("order by") || filter.contains("ORDER BY"))) {
            LoggerUtils.warn("[LazyEntityDataModel] can not contains order by");
        } else {
            this.filter = filter;
        }

        this.baseDao = baseDao;
    }

    public LazyEntityDataModel(BaseDao<T> baseDao) {
        this.baseDao = baseDao;
    }

    //  public LazyEntityDataModel(int rowCount) {
    //    super.setRowCount(rowCount);
    /// }
    @Override
    //TODO: change to entity id from view
    public T getRowData(String rowKey) {
        List<T> list = (List<T>) getWrappedData();
        //TODO:try
//        Long id = Long.valueOf(rowKey);
        if (!list.isEmpty()) {
            for (T t : list) {
//                if (t.getId() == id) {
                if (t.getId().equals(rowKey)) {
                    return t;
                }
            }
        }

        return null;
    }

    @Override
    public List<T> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, String> filters) {
        setRowCount(baseDao.findByConditionRowCount(filters, filter));
        return baseDao.findByCondition(first, pageSize, filters, sortField, sortOrder, filter);
    }

    @Override
    public void setRowIndex(int rowIndex) {
        if (rowIndex == -1 || getPageSize() == 0) {
            super.setRowIndex(-1);
        } else {
            super.setRowIndex(rowIndex % getPageSize());
        }
    }

    @Override
    public Object getRowKey(T object) {
        return object.getId();
    }
    
}
